<?php

namespace dk\widget;

class Clean extends Base {
    use \dk\traits\Singleton;

    /**
     * @param \weixin\core\View $plug
     */
    function bindHandle($plug) {
        $plug->regPlug("clean", array($this, "render"));
    }

    /**
     * @param $files
     * @return string
     */
    function render($content){
        $content = $this->clearXss($content);
        $content = $this->fix($content);
        $content = $this->imgResponsive($content);
        return $content;
    }

    public static function clearXss($string){
        $string = preg_replace('/<a.*?>(.+?)<\/a>/is', '$1', $string);
        $string = preg_replace('/<script.+?<\/script\>/is', '', $string);
        $string = preg_replace('/<iframe.+?<\/iframe\>/is', '', $string);
        $string = preg_replace('/<object.+?<\/object\>/is', '', $string);
        $string = preg_replace('#http://[a-zA-Z0-9]+\.bmlink.com#is', '', $string);
        //$string = preg_replace('#http://[0-9a-zA-Z\.\/\%\?=]+#es', "JRequest::clearLink('\\0')", $string);
        return $string;
    }

    public static function fix($html, $charset = 'gbk'){
        if(!function_exists('tidy_repair_string'))
            return $html;

        $string = tidy_repair_string(
            mb_convert_encoding($html, 'utf8', $charset),
            array(
                'output-xhtml' => true,
                'output-html'=>true,
                'show-body-only' => true,
                'drop-proprietary-attributes' => true,
                'drop-font-tags' => true,
                'clean' => true,
            ),
            'utf8'
        );

        return mb_convert_encoding($string, $charset, 'utf8');
    }

    public static function imgResponsive($content){
        return preg_replace_callback('/<img.+?>/is', function($matches){
            $img = $matches[0];
            if(!stripos($img, 'img-responsive')){
                if(!stripos($img, 'class')){
                    return str_ireplace('<img', '<img class="img-responsive"', $img);
                }else{
                    $img = str_replace(array("\r", "\n"), '', $img);
                    return preg_replace('#class=(["\'])#is', 'class=$1img-responsive ', $img);
                }
            }
            return $img;
        }, $content);
    }
}